// utils/request.js
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 确保 URL 是完整的
    if (!options.url.startsWith('http')) {
      options.url = 'http://8.137.157.16:9999' + options.url;
    }

    uni.request({
      ...options,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

// 添加请求拦截器
request.interceptors = {
  request: (config) => {
    // 在这里添加请求拦截逻辑
    const user = uni.getStorageSync('user');
    if (user) {
      config.header.Authorization = `Bearer ${user.token}`;
    }
    return config;
  },
  response: (response) => {
    // 在这里添加响应拦截逻辑
    return response;
  },
};

// 添加 get 方法
request.get = (url, config) => {
  return request({
    url,
    method: 'GET',
    ...config,
  });
};

// 添加 post 方法
request.post = (url, data, config) => {
  return request({
    url,
    method: 'POST',
    data,
    ...config,
  });
};

export default request;